/**
 * @desc 请求封装
 * @auth 韩
 */

import { XxNotification } from "@/ui";
import { message } from "antd";
import axios from "axios";
import { outLogin } from "@/api/user"

let baseUrl = import.meta.env.VITE_APP_BASE_URL;

// 创建axios实例 ，设置默认请求配置
const instance = axios.create({
    timeout: 60000,//超时时间
    baseURL: baseUrl//基本路由
})

//统一设置post请求头
instance.defaults.headers.post['Content-Type'] = "application/json";

// 如果你是上传文件的话需要设置为
// instance.defaults.headers.post['Content-Type'] = 'multipart/form-data';


//请求拦截器
instance.interceptors.request.use(config => {
    var token = sessionStorage.token;//获取缓存中的token

    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;//在请求头中加上token
    }



    return config;
}, error => {
    console.log("error请求错误", error)
    return Promise.reject(error)
})


// 响应拦截 判断数据是否正常完好，再把数据返回到发请求的地方
instance.interceptors.response.use(response => {
    if (response.status === 200) {
        // token过期了跳转登录页面
        if (response.data.status === "1001") {
            message.warn("身份验证过期，请重新登录");
            setTimeout(() => {
                outLogin()
            }, 2000)
            return;
        }
        return Promise.resolve(response.data)
    } else {
        return Promise.reject(response.data.msg)
    }
}, error => {
    //请求报错的回调，对不同状态码进行处理
    console.log("请求报错：\n", error)
    if (error.response) {
        if (error.response.status === 401) {
            outLogin()
        }
        return Promise.reject(error)
    } else {
        return Promise.reject("请求超时，请重试");
    }
})


// 封装get请求
const get = (url, params, config = {}) => {
    return new Promise((resolve, reject) => {
        instance({
            method: "get",
            url,
            params,
            ...config
        }).then(response => {
            resolve(response)
        }).catch(error => {
            reject(error)
        })
    })
}

//封装post请求
const post = (url, data, config = {}) => {
    return new Promise((resolve, reject) => {
        instance({
            method: 'post',
            url,
            data,
            ...config
        }).then(response => {
            resolve(response)
        }).catch((error) => {
            reject(error)
            XxNotification({ text: error, type: "error" })
        })
    })
}



// 封装文件上传(二进制流上传)
const upload = ({
    url = "",
    data,
    params = {},
    headers = {}
}) => {
    return new Promise((resolve, reject) => {
        instance({
            method: "POST",
            url,
            params: { ...params },
            data,
            headers: {
                "Content-Type": "multipart/form-data",
                ...headers
            }
        }).then(response => {
            resolve(response)
        }).catch(error => {
            reject(error)
        })
    })
}

// 封装http  upload上传，
const http = {
    post: async ({
        url = String,
        params = Object,
        before = () => { },
        success = () => { },
        failure = () => { },
        complete = () => { }
    }) => {
        try {
            before();
            const res = await post(url, {
                ...params,
            })
            if (res.status === "0000") {
                success(res)
            } else {
                failure(res.message)
            }
        } catch (error) {
            console.log(error)
            failure("网络连接失败")
        } finally {
            complete()
        }
    },
    get: async ({
        url = String,
        params = Object,
        before = Function,
        success = Function,
        failure = Function,
        complete = Function
    }) => {
        before()
        try {

            const res = await get(url, {
                ...params,
            })

            if (res.code === 0) {
                success(res)
            } else {
                failure(res.message)
            }
        } catch (error) {
            console.log(error)
            failure("网络连接失败")
        } finally {
            complete()
        }
    },
    upload: async ({
        url = String,
        params = Object,
        before = Function,
        success = Function,
        failure = Function,
        complete = Function
    }) => {
        before();
        try {
            let formData = new FormData();
            formData.append(params.filename || 'file', params.file)
            const res = await upload({
                url,
                data: formData,
            })
            console.log("文件上传结果：", res)
            if (res.code === '0000') {
                success(res)
            } else {
                failure(res.message)
            }
        } catch (error) {
            console.log("文件上传catch：", error)
            failure("文件无法上传，网络连接失败")
        } finally {
            complete()
        }
    }
}


export default http;